import React,{useState,useEffect,useLayoutEffect} from 'react'
import { StyleSheet,View,Text,Image,
         ScrollView,Modal,Button,TouchableOpacity,
         ImageBackground,
         TextInput
        } from 'react-native'
import { AntDesign } from '@expo/vector-icons';
import { FontAwesome } from '@expo/vector-icons';
import { FontAwesome5 } from '@expo/vector-icons';
import '../global' 
import AsyncStorage from '@react-native-async-storage/async-storage';
import { backgroundColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes';
const Detail = ({route,navigation}) => {

    const [show,setShow] = useState(false);

    const [percomment,setPercomment]=useState()

    const [topicid,setTopicid]=useState(route.params.detailObj.id)

    const [user,setUser]=useState(user_info)

    const [comment,setComment]=useState([

      {

        id:0,

        comment_topic_id:0,

        comment_user_id:1,

        comment_user_name:'',

        comment_user_avatar:'',

        comment_content:'',

        topic_imag:'',

        comment_number_of_likes:0,

        updatedAt:''

      }

    ])

    const [commentValue,setCommentValue]=useState()

    const[iscollect,setIscollect]=useState(false)
    const[islike,setIslike]=useState(false)

    const [collected,setCollected]=useState([{

      "topic": {

          "id": 2,

          "topic_user_id": 6,

          "topic_user_name": "笑哈哈",

          "topic_user_avatar": "http://82.157.94.91:8000/defaultAvatar.jpg",

          "topic_type": "english",

          "topic_title": "怎么背单词才高效呢?",

          "topic_content": "如题，单词书特别厚，怎么才能高效的记忆单词嘞",

          "topic_img": '',

          "topic_number_of_likes": 86,

          "createdAt": "2022-04-24T08:52:40.000Z",

          "updatedAt": "2022-04-24T08:52:40.000Z"

      },

      "comment_mes": [

      ]

  }

  ])

      useEffect(()=>{fetch('http://82.157.94.91:8000/users/get_user_collects',{

          method:'post',

          headers: {

             'Content-Type': 'application/json',

             'Authorization':"Bearer "+token

          },

          body:JSON.stringify({

              user_id:user.id,

          })

        })

        .then(res=>res.json())

        .then(res=>{

           setCollected(res.result)

          })

        .then(res=>{

           const collectTopic = collected.filter((item) => item.topic.id==topicid);

          if(collectTopic.length==0){

            setIscollect(false)

          }else{

            setIscollect(true)

          }

        })},[collected])

    const like=(id)=>{
      if(islike==false){
          fetch('http://82.157.94.91:8000/topics/like_post',{

                method:'post',

                headers: {

                 'Content-Type': 'application/json',

                },

                body:JSON.stringify({

                collect_topic_id:topicid

               })

              })

         .then(res=>res.json())

         .then(res=>{

           setIslike(true)

          })
         }else{
          fetch('http://82.157.94.91:8000/topics/dislike_post',{

            method:'post',

            headers: {

             'Content-Type': 'application/json',

            },

            body:JSON.stringify({

            collect_topic_id:topicid

           })

          })

        .then(res=>res.json())

        .then(res=>{

         setIslike(false)

      })
         }
     }

    const collect=()=>{

      if (iscollect==false){

      fetch('http://82.157.94.91:8000/users/collect_topic',{

        method:'post',

        headers: {

           'Content-Type': 'application/json',

           'Authorization':"Bearer "+token

        },

        body:JSON.stringify({

            user_id:user.id,

            collect_topic_id:topicid

        })

      })

      .then(res=>res.json())

      .then(res=>{

        setIscollect(true)

      })

    }else{

      fetch('http://82.157.94.91:8000/users/delete_collect_topic',{

        method:'post',

        headers: {

           'Content-Type': 'application/json',

           'Authorization':"Bearer "+token

        },

        body:JSON.stringify({

            user_id:user.id,

            collect_topic_id:topicid

        })

      })

      .then(res=>res.json())

      .then(res=>{

        setIscollect(false)

      })

    }

  }

    const lookcomment=()=>{

      setShow(true);

      fetch('http://82.157.94.91:8000/topics/get_topic_comments/'+topicid)

      .then(res=>res.json())

      .then(res=>{

        setPercomment(res.result)

        setComment(res.result)

      })

    }

    const publishcommment=()=>{

      fetch('http://82.157.94.91:8000/topics/post_comment',{

        method:'post',

        headers: {

           'Content-Type': 'application/json',

           'Authorization':"Bearer "+token

        },

        body:JSON.stringify({

          comment_topic_id:topicid,

          comment_user_id:user.id,

          comment_user_name:user.user_name,

          comment_user_avatar:user.user_avatar,

          comment_content:commentValue,

          topic_img:null

        })

      })

      .then(res=>res.json())

      .then(res=>{

        lookcomment()

      })

       

    }

    useLayoutEffect(()=>{

        navigation.setOptions({

         title:route.params.txt,

         headerStyle: {
             height:pxtodpH(10),
             backgroundColor: 'dodgerblue',

         },

         headerTintColor: 'white',

         headerTitleAlign: 'center',

        }) 

        },[])

   return(

       <View>


       <ScrollView>  

           <Text style={styles.title}>{route.params.detailObj.topic_title}</Text>

           <View style={styles.introduce}>

           <Image style={styles.head} 

                   source={{

                                uri: route.params.detailObj.topic_user_avatar,

                              }}/>

          <Text style={styles.name}>{route.params.detailObj.topic_user_name}</Text>

           </View>

           <View>

               <Text style={{marginLeft:pxtodpW(15),marginTop:pxtodpH(10),fontSize:15}}>{route.params.detailObj.topic_content}</Text>

                 {route.params.detailObj.topic_img!=null? <Image 

                   style={styles.topicimg}

                   source={{

                                uri: route.params.detailObj.topic_img

                              }}

                />:null}


           </View>

        </ScrollView>

        <View style={styles.usersaction}>

        <TouchableOpacity onPress={()=>{lookcomment()}}>

           <FontAwesome5 name="comment-alt" size={28} color="black" style={{marginTop:pxtodpH(10)}}/>

        </TouchableOpacity>

        <TouchableOpacity onPress={()=>{like()}}>

           <AntDesign name="like2" size={32} color={islike==true?'blue':'black'} style={{marginLeft:pxtodpW(15)}} />

        </TouchableOpacity>
        <TouchableOpacity onPress={()=>{collect()}}>

         <AntDesign name="hearto" size={32} color={iscollect==true?'blue':'black'} style={{marginLeft:pxtodpW(10)}} />

        </TouchableOpacity>


        </View>

        <Modal

          animationType="slide"

          transparent={false}

          visible={show}

          onRequestClose={() => {

            setShow(!show);

          }}

        > 
          <View style={{  display:'flex',

                         flexDirection:'row',

                         height:pxtodpH(70),
                         backgroundColor:'dodgerblue'

                         }}>

          <Text style={{fontSize:20,textAlign:'center',marginLeft:pxtodpW(300)}}>全部评论</Text>

          <TouchableOpacity onPress={()=>{setShow(false)}}>

                <FontAwesome style={{marginLeft:pxtodpW(200)}} name="close" size={24} color="black" />

          </TouchableOpacity>

          </View>

          <ScrollView style={styles.showcomment}>

           {

               comment.map((item,id)=>{

                   return(

                       <View style={styles.commentdetail}>

                           <View style={styles.commentuser}>

                               <Image 

                                 style={styles.commenthead}

                                 source={{

                                  uri: item.comment_user_avatar,

                                }}

                               />

                               <Text style={{lineHeight:pxtodpH(80),marginLeft:pxtodpW(10),fontSize:15}}>{item.comment_user_name}</Text>

                           </View>

                           <Text style={styles.commenttext}>{item.comment_content}</Text>

                           <Text style={{marginLeft:pxtodpW(10),marginTop:pxtodpH(10),fontSize:10,color:'grey'}}>最新回复于{item.updatedAt}</Text>
                           <View style={{width:pxtodpW(750),height:pxtodpH(3),backgroundColor:'lightgrey',marginTop:pxtodpH(10)}}></View>

                       </View>

                   )

               })



           }

           

          </ScrollView>

          {/* </ImageBackground> */}

          <View style={styles.comment}>
            
          <Image   style={styles.commenthead} 

              source={{

              uri: route.params.detailObj.topic_user_avatar,

           }}/>

             <TextInput 

                placeholder='发一条友善的评论'

                value={commentValue}

                onChangeText={(text)=>{setCommentValue(text)}}

                style={styles.input}

             />

             <TouchableOpacity onPress={()=>{publishcommment()}}>
               <Text
                 style={{
                  width:pxtodpW(80),
                  marginTop:pxtodpH(15),
                  textAlign:'center',
                  backgroundColor:'dodgerblue',
                  height:pxtodpH(50),
                  marginLeft:pxtodpH(15),
                  borderRadius:15,
                  fontSize:15
                }}
               >发布</Text>
             </TouchableOpacity> 

          </View>

        </Modal>

        </View>

   )

}

const styles = StyleSheet.create({

   title:{

       fontSize:23,
       marginLeft:pxtodpW(15)

   },

   background:{

    width:pxtodpW(750),

    height:pxtodpH(1200),

},

comment_background:{

  width:pxtodpW(750),

    height:pxtodpH(1090),

},

   introduce:{

    width:pxtodpW(750),

    height:pxtodpH(100),

    display:'flex',

    flexDirection:'row',
    marginTop:pxtodpH(10)

   },

   head:{

    width:pxtodpW(100),

    height:pxtodpH(100),

    marginLeft:pxtodpW(15),
    borderRadius:15

   },

   name:{
       fontSize:18,
       marginLeft:pxtodpW(15),
       lineHeight:pxtodpH(100)
       

   },

   usersaction:{

    display:'flex',

    flexDirection:'row',

    marginLeft:pxtodpW(550),
    marginTop:pxtodpH(10)

   },

   topicimg:{

    width:pxtodpW(750),

    height:pxtodpH(700),

    borderWidth:1,

    resizeMode:'contain',
    marginTop:pxtodpH(20)

   },

   showcomment:{

    width:pxtodpW(700),

    height:pxtodpH(500),
    marginLeft:pxtodpW(30),

   },

   comment:{

    width:pxtodpW(700),

    height:pxtodpH(100),

    marginLeft:pxtodpW(10),

    display:'flex',

    flexDirection:'row',

    justifyContent:"space-around",

   },

   input:{

    marginLeft:pxtodpW(10),

    width:pxtodpW(550),

    height:pxtodpH(80),
    color:'black',
    backgroundColor:'#eee',
    borderRadius:15
   },
commentdetail:{
  marginBottom:pxtodpH(10),
},
   commentuser:{
    marginTop:pxtodpH(10),
    display:'flex',
    flexDirection:'row',
   },
   commenthead:{
    width:pxtodpW(80),
    height:pxtodpH(80),
    borderColor:'black',
    borderWidth:1,
    marginRight:pxtodpW(10),
    borderRadius:25
   },
   commenttext:{
     marginLeft:pxtodpW(10),
     marginTop:pxtodpH(10),
     fontSize:13
   },
});

export default Detail